import { NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { prisma } from '@/lib/db';

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, email, password } = body;

    console.log('注册请求数据:', { name, email, passwordLength: password?.length });

    // 验证请求数据
    if (!name || !email || !password) {
      console.log('注册验证失败: 缺少必要字段', { name: !!name, email: !!email, password: !!password });
      return NextResponse.json(
        { message: '姓名、邮箱和密码都是必填项' },
        { status: 400 }
      );
    }

    try {
      // 检查邮箱是否已被注册
      const existingUser = await prisma.user.findUnique({
        where: { email },
      });

      if (existingUser) {
        console.log('注册失败: 邮箱已存在', { email });
        return NextResponse.json(
          { message: '该邮箱已被注册' },
          { status: 409 }
        );
      }

      // 对密码进行加密
      const hashedPassword = await bcrypt.hash(password, 10);
      console.log('密码加密成功');

      // 创建新用户
      const user = await prisma.user.create({
        data: {
          name,
          email,
          password: hashedPassword,
        },
      });

      console.log('用户创建成功:', { id: user.id, email: user.email });

      // 返回创建成功的用户信息（不包含密码）
      return NextResponse.json({
        id: user.id,
        name: user.name,
        email: user.email,
        createdAt: user.createdAt,
      }, { status: 201 });
    } catch (dbError: any) {
      console.error('数据库操作失败:', dbError);
      return NextResponse.json(
        { message: '数据库操作失败: ' + (dbError.message || '未知错误') },
        { status: 500 }
      );
    }
  } catch (error: any) {
    console.error('注册过程中发生错误:', error);
    return NextResponse.json(
      { message: '注册过程中发生错误，请稍后重试: ' + (error.message || '未知错误') },
      { status: 500 }
    );
  }
} 